package bbs.web.servlet;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;

import bbs.bean.Article;
import bbs.bean.User;
import bbs.dao.ArticleDao;
import bbs.dao.CollectDao;

/**
 * 用户收藏文章的Servlet
 */

@WebServlet("/collect.s")
public class UserCollectServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	CollectDao dao = new CollectDao();
	ArticleDao dao2 = new ArticleDao();
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=utf-8");
		String tid = request.getParameter("tid");
		
		User user =  (User) request.getSession().getAttribute("loginedUser");
		String uid=  user.getUid();
		
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		String cdate = df.format(new Date());
		//查该用户是否收藏了该文章
		//先在数据库查询该篇文章
		List list = dao.selectCollection2(uid,tid);
		System.out.println(list);
		//hash map list==> “null”值map对象为空，要查看对象的集合是否为空用size()
		if(list.size()==0){
			dao.insertCollect(tid, cdate, uid);
			String json = new Gson().toJson("收藏成功！");
			response.getWriter().append(json);
			System.out.println(tid+""+cdate);
		}else{
			String json = new Gson().toJson("您已收藏了该文章！");
			response.getWriter().append(json);
		}
	}
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
